<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <!-- 图片，用来展示用户选择的头像 -->
      <img src="../../../assets/images/avatar.jpg" alt="" class="preview" v-if="avatar === ''" />
      <img :src="avatar" alt="" class="preview" v-else />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <!-- <input type="file"(调用浏览器选择文件的能力) accept="image/*"(只能选择图片) style="display: none"(隐藏) ref="fileRef" /> -->
        <input type="file" accept="image/*" style="display: none" ref="fileRef" @change="fileChange" />
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="avatar === ''" @click="uploadAvatar"
          >上传头像</el-button
        >
      </div>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'UserAvatar',
  data() {
    return {
      avatar: ''
    }
  },
  methods: {
    chooseImg() {
      this.$refs.fileRef.click()
    },
    fileChange(e) {
      // 存放图片的数组(伪数组)
      const files = e.target.files
      if (files.length === 0) {
        console.log('没有选择图片')
      } else {
        console.log('选择了图片')
        console.log(files[0])
        const fr = new FileReader()
        fr.readAsDataURL(files[0])
        fr.onload = e => {
          // console.log(e.target.result)
          this.avatar = e.target.result
        }
      }
    },
    async uploadAvatar() {
      const { data: res } = await this.$http.patch('/my/update/avatar', {
        avatar: this.avatar
      })
      if (res.code === 0) {
        // 上传头像成功,提示用户
        this.$message.success(res.message)
        // 调用用户信息接口,获取用户的最新的信息
        this.$store.dispatch('getUserInfo')
      } else {
        // 长传头像失败,提示用户
        this.$message.error(res.message)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  width: 350px;
  height: 350px;
  object-fit: cover;
}
</style>
